package com.yima.baseproj.module.app.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yima.baseproj.module.app.Controller.model.*;
import com.yima.baseproj.module.app.Controller.personnelModel.*;
import com.yima.baseproj.module.app.equipmentDevice.EquipmentDeviceService;
import com.yima.baseproj.module.app.equipmentEquipment.EquipmentEquipmentEntity;
import com.yima.baseproj.module.app.equipmentEquipment.EquipmentEquipmentService;
import com.yima.baseproj.module.app.equipment_entry.EquipmentEntryService;
import com.yima.baseproj.module.app.user.AppUserEntity;
import com.yima.baseproj.module.app.user.AppUserService;
import com.yima.baseproj.security.SecurityUtil;
import com.yima.baseproj.utils.*;
import com.yima.baseproj.utils.Error.MessageConstant;
import org.json.JSONObject;
import com.yima.baseproj.module.config.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.yima.baseproj.utils.JsonUtils.admitRemoveJson;
import static com.yima.baseproj.utils.JsonUtils.settingUpdateJson;


@Api(tags = "门禁")
@RequestMapping("/api/app/access")
@RestController
public class accessController extends BaseController {
    //设备号 E03C1CB2252FAA02
    @Resource
    private EquipmentEquipmentService equipmentEquipmentService;
    //项目GUID
    private static final String PROJECT_GUID = "52A5A9157E3942AE830EFC1D6AB2A86F";
    @Resource
    private AppUserService appUserService;

    @Resource
    private EquipmentDeviceService equipmentDeviceService;
    @Resource
    private EquipmentEntryService equipmentEntryService;

    @ApiOperation("新增设备")
    @PostMapping(value = "/addCreate")
    public R<String> addCreate(AddCreateModel addCreateModel) throws Exception {

        int selectByDeviceNo = equipmentEntryService.selectByDeviceNo(addCreateModel.getDeviceNo());
        System.out.println("selectByDeviceNo: " + selectByDeviceNo);

        if (selectByDeviceNo == 0) {
            return R.error("请绑定本厂商的设备");
        }

        int DeviceNo = equipmentEquipmentService.getOneList(addCreateModel.getDeviceNo());
        if (DeviceNo == 1) {
            return R.error("设备已被绑定");
        }

        String url = "/v2/device/create"; // 替换为你要发送请求的URL
        addCreateModel.setSource("000000");
        addCreateModel.setAddition("{'recType':'1'}");
        String JsonData = StringToJsonConverter.convertToJson(addCreateModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        JSONObject jsonObject = new JSONObject(response);
        String msg = jsonObject.getString("msg");
        AppUserEntity byId = appUserService.getById(SecurityUtil.getUserId());

        if (DeviceNo == 0) {
            if (msg.contains("success") || DeviceNo != 0) {
                EquipmentEquipmentEntity equipment = new EquipmentEquipmentEntity();
                equipment.setUserOpenid(byId.getMpWeixinOpenId());
                equipment.setName(addCreateModel.getName());
                equipment.setTag(addCreateModel.getTag());
                equipment.setSceneguid(addCreateModel.getSceneGuid());
                equipment.setSource(addCreateModel.getSource());
                equipment.setDeviceno(addCreateModel.getDeviceNo());
                equipment.setAddition(addCreateModel.getAddition());
                equipmentEquipmentService.save(equipment);
                OnlineStateModel onlineStateModel = new OnlineStateModel();
                onlineStateModel.setDeviceNos(addCreateModel.getDeviceNo());
                R<String> stringR = onlineState(onlineStateModel);
                System.out.println("stringR:---" + stringR);
                String onlinestate = JsonUtils.JsonData(String.valueOf(stringR));
                JSONObject jsonMsg = new JSONObject(onlinestate);
                String JSONMsg = jsonMsg.getString("msg");
                String JData = jsonMsg.getString("data");
                if (JSONMsg.contains("success")) {
                    boolean aTrue = JData.contains("online");
                    if (aTrue) {
                        OnlineLine(addCreateModel.getDeviceNo(), 1);
                    } else {
                        OnlineLine(addCreateModel.getDeviceNo(), 2);
                    }
                }
            }
        }
        return R.success(response, "操作成功");
    }

    /**
     * 设备上线 设备下线
     */
    private void OnlineLine(String deviceNo, int status) {
        System.out.println("设备上线 设备下线   设备序列号： " + deviceNo + " 状态： " + status);
        EquipmentEquipmentEntity one = equipmentEquipmentService.getOneL(deviceNo);
        if (one != null) {
            one.setStatus(status);
        }
        equipmentEquipmentService.updateById(one);
    }

    @ApiOperation("修改设备")
    @PostMapping(value = "/update")
    public R<String> update(@Validated AddCreateModel addCreateModel) throws Exception {
        String url = "/v2/device/update"; // 替换为你要发送请求的URL
        addCreateModel.setSource("000000");
        addCreateModel.setAddition("{'recType':'1'}");
        String JsonData = StringToJsonConverter.convertToJson(addCreateModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        JSONObject jsonObject = new JSONObject(response);
        String msg = jsonObject.getString("msg");
//        LambdaQueryWrapper<EquipmentEquipmentEntity> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(EquipmentEquipmentEntity::getDeviceno, addCreateModel.getDeviceNo());
//        EquipmentEquipmentEntity one = equipmentEquipmentService.getOne(queryWrapper);
        EquipmentEquipmentEntity oneL = equipmentEquipmentService.getOneL(addCreateModel.getDeviceNo());
        System.out.println("noel" + oneL);
        AppUserEntity byId = appUserService.getById(SecurityUtil.getUserId());
        if (msg.contains("success") || oneL != null) {
            EquipmentEquipmentEntity equipment = new EquipmentEquipmentEntity();
            equipment.setId(oneL.getId());
            equipment.setUserOpenid(byId.getMpWeixinOpenId());
            equipment.setName(addCreateModel.getName());
            equipment.setTag(addCreateModel.getTag());
            equipment.setSceneguid(addCreateModel.getSceneGuid());
            equipment.setSource(addCreateModel.getSource());
            equipment.setDeviceno(addCreateModel.getDeviceNo());
            equipment.setAddition(addCreateModel.getAddition());
            equipment.setStatus(1);
            equipmentEquipmentService.updateById(equipment);


        }
        return R.success(response, "操作成功");
    }

    @ApiOperation("删除设备")
    @PostMapping(value = "/delete")
    public R<String> delete(@Validated DetailModel detailModel) throws Exception {
        System.out.println(detailModel.getDeviceNo());


        String url = "/v2/device/delete"; // 替换为你要发送请求的URL
        detailModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJson(detailModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        JSONObject jsonObject = new JSONObject(response);
        String msg = jsonObject.getString("msg");
        if (msg.contains("success")) {
            boolean del = equipmentEquipmentService.delNO(detailModel.getDeviceNo());
            boolean equipmentDeviceDel = equipmentDeviceService.delNO(detailModel.getDeviceNo());

            System.out.println("del:------" + del);
            System.out.println("equipmentDeviceDel:------" + equipmentDeviceDel);

        }
        return R.success(response, "操作成功");
    }

    @ApiOperation("删除绑定用户")
    @PostMapping(value = "/deleteWeb")
    public R<String> deleteWeb(@Validated @RequestBody DetailModel detailModel) throws Exception {
        System.out.println(detailModel.getDeviceNo());

        String url = "/v2/device/delete"; // 替换为你要发送请求的URL
        detailModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJson(detailModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        JSONObject jsonObject = new JSONObject(response);
        String msg = jsonObject.getString("msg");
        if (msg.contains("success")) {
            boolean del = equipmentEquipmentService.delNO(detailModel.getDeviceNo());
            boolean equipmentDeviceDel = equipmentDeviceService.delNO(detailModel.getDeviceNo());

            System.out.println("del:------" + del);
            System.out.println("equipmentDeviceDel:------" + equipmentDeviceDel);

        }
        return R.success(response, "操作成功");
    }


    @ApiOperation("设备详情")
    @PostMapping(value = "/detail")
    public R<String> detail(@Validated DetailModel detailModel) throws Exception {
        String url = "/v2/device/detail"; // 替换为你要发送请求的URL
        detailModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJson(detailModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("设备列表")
    @PostMapping(value = "/page")
    public R<String> page(@Validated PageModel pageModel) throws Exception {
        String url = "/v2/device/page"; // 替换为你要发送请求的URL
        pageModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJson(pageModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("设备配置修改")
    @PostMapping(value = "/settingUpdate")
    public R<String> upd(QueryModel queryModel) throws Exception {
        String url = "/v2/device/setting/update"; // 替换为你要发送请求的URL
        String JsonData = settingUpdateJson(queryModel.getDeviceNo(), "000000", queryModel.getDeviceConfigs());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("设备配置查询")
    @PostMapping(value = "/query")
    public R<String> query(@Validated QueryModel queryModel) throws Exception {
        String url = "/v2/device/setting/query"; // 替换为你要发送请求的URL
        queryModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJsonTow(queryModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("查询固件包列表")
    @PostMapping(value = "/devicePackage")
    public R<String> devicePackage(@Validated devicePackageModel devicePackageModel) throws Exception {
        String url = "/v2/device/devicePackage"; // 替换为你要发送请求的URL
        devicePackageModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJson(devicePackageModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("设备在线状态批量查询")
    @PostMapping(value = "/onlineState")
    public R<String> onlineState(@Validated OnlineStateModel onlineStateModel) throws Exception {
        String url = "/v2/device/onlineState"; // 替换为你要发送请求的URL
        onlineStateModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJsonTow(onlineStateModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("设备操作指令下发（重启/重置）")
    @PostMapping(value = "/command")
    public R<String> command(@Validated CommandModel commandModel) throws Exception {
        String url = "/v2/device/command"; // 替换为你要发送请求的URL
        commandModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJson(commandModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("设备升级")
    @PostMapping(value = "/upgrade")
    public R<String> upgrade(@Validated UpgradeModel upgradeModel) throws Exception {
        String url = "/v2/device/upgrade"; // 替换为你要发送请求的URL
        upgradeModel.setSource("000000");
        String JsonData = StringToJsonConverter.convertToJson(upgradeModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("设备注册任务")
    @PostMapping(value = "/registerMode")
    public R<String> registerMode(@Validated RegisterModel registerModel) throws Exception {
        String url = "/v2/device/registerMode"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJson(registerModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("设备注册任务查询")
    @PostMapping(value = "/registerModeQuery")
    public R<String> registerModeQuery(@Validated RegisterModelQuery registerModelQuery) throws Exception {
        String url = "/v2/device/registerMode/query"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJson(registerModelQuery.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("远程开门")
    @PostMapping(value = "/interactive")
    public R<String> interactive(@Validated InteractiveModel interactiveModel) throws Exception {
        String url = "/v2/device/interactive"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJson(interactiveModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    /**
     * 人员接口
     */

    @ApiOperation("识别主体创建")
    @PostMapping(value = "/admitCreate")
    public R<String> admitCreate(@Validated SubjectModel subjectModel) throws Exception {
        String url = "/v2/admit/create"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJson(subjectModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("人像注册")
    @PostMapping(value = "/faceRegister")
    public R<String> faceRegister(FaceRegisterModel faceRegisterModel) throws Exception {
        String url = "/v2/face/register"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.extractContentImage(faceRegisterModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("设备授权识别主体")
    @PostMapping(value = "/authDevice")
    public R<String> device(AuthDevicemodel authDevicemodel) throws Exception {
        String url = "/v2/auth/device"; // 替换为你要发送请求的URL
        String JsonData = String.valueOf(AuthDeviceJson.authDeviceJson(authDevicemodel));
        String token = CacheUtil.getValue("authenticationToken");
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }


    @ApiOperation("设备销权识别主体")
    @PostMapping(value = "/deviceRevoke")
    public R<String> deviceRevoke(@Validated AuthDevicemodel authDevicemodel) throws Exception {
        String url = "/v2/auth/device/revoke"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJsonTow(authDevicemodel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }


    @ApiOperation("识别主体更新")
    @PostMapping(value = "/admitUpdate")
    public R<String> admitUpdate(@Validated SubjectModel subjectModel) throws Exception {
        String url = "/v2/admit/update"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJson(subjectModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("识别主体删除")
    @PostMapping(value = "/admitDelete")
    public R<String> admitDelete(@Validated AdmitDelete admitDelete) throws Exception {
        String url = "/v2/admit/delete"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJsonTow(admitDelete.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        JSONObject admit = new JSONObject(response);
        String admitDeleteMsg = admit.getString("msg");

        if (admitDeleteMsg.contains("success")) {
            equipmentDeviceService.UpdType(admitDelete.getAdmitGuids());
        }
        return R.success(response, "操作成功");
    }


    @ApiOperation("查询识别主体详情")
    @PostMapping(value = "/admitDetail")
    public R<String> admitDetail(@Validated SubjectModel subjectModel) throws Exception {
        String url = "/v2/admit/detail"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJson(subjectModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("识别主体列表")
    @PostMapping(value = "/admitPage")
    public R<String> admitPage(@Validated AdmitPageModel admitPageModel) throws Exception {
        String url = "/v2/admit/page"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJsonTow(admitPageModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }


    @ApiOperation("人像删除")
    @PostMapping(value = "/faceDelete")
    public R<String> faceDelete(@Validated FaceRegisterModel faceRegisterModel) throws Exception {
        String url = "/v2/face/delete"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJsonTow(faceRegisterModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("人员照片信息查询")
    @PostMapping(value = "/faceDetail")
    public R<String> faceDetail(@Validated FaceRegisterModel faceRegisterModel) throws Exception {
        String url = "/v2/face/detail"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJsonTow(faceRegisterModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    @ApiOperation("指纹注册")
    @PostMapping(value = "/fingerprintCreate")
    public R<String> fingerprintCreate(@Validated FingerprintCreateModel fingerprintCreateModel) throws Exception {
        String url = "/v2/fingerprint/create"; // 替换为你要发送请求的URL
        String JsonData = StringToJsonConverter.convertToJson(fingerprintCreateModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);

        return R.success(response, "操作成功");
    }

    /**
     * 场景接口
     */

    @ApiOperation("创建场景")
    @PostMapping(value = "/sceneCreate")
    public R<String> sceneCreate(@Validated SceneCreateModel appCreateModel) throws Exception {
        String url = "/v2/scene/create";
        String JsonData = StringToJsonConverter.convertToJson(appCreateModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("编辑场景")
    @PostMapping(value = "/sceneUpdate")
    public R<String> sceneUpdate(@Validated SceneCreateModel appCreateModel) throws Exception {
        String url = "/v2/scene/update";
        String JsonData = StringToJsonConverter.convertToJson(appCreateModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("删除场景")
    @PostMapping(value = "/sceneDelete")
    public R<String> sceneDelete(@Validated SceneCreateModel appCreateModel) throws Exception {
        String url = "/v2/scene/delete";
        String JsonData = StringToJsonConverter.convertToJson(appCreateModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("查询场景列表")
    @PostMapping(value = "/scenePage")
    public R<String> scenePage(@Validated ScenePageModel scenePageModel) throws Exception {
        String url = "/v2/scene/page";
        String JsonData = StringToJsonConverter.convertToJson(scenePageModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("场景添加识别主体")
    @PostMapping(value = "/admitAdd")
    public R<String> admitAdd(AdmitAddModel admitAddModel) throws Exception {
        Map<String, Object> dataMap = new HashMap<>();
        if (admitAddModel.getSceneGuid() != null && admitAddModel.getSceneGuid() != "") {
            dataMap.put("sceneGuid", admitAddModel.getSceneGuid());
        }
        if (admitAddModel.getAdmitGuids() != null && admitAddModel.getAdmitGuids() != "") {
            dataMap.put("admitGuids", admitAddModel.getAdmitGuids());
        }
        if (admitAddModel.getType() != null && admitAddModel.getType() != "") {
            dataMap.put("type", admitAddModel.getType());
        }
        if (admitAddModel.getPassTime() != null && admitAddModel.getPassTime() != "") {
            dataMap.put("passTime", admitAddModel.getPassTime());
        }
        if (admitAddModel.getPermissionTime() != null && admitAddModel.getPermissionTime() != "") {
            dataMap.put("permissionTime", admitAddModel.getPermissionTime());
        }
        if (admitAddModel.getPermission() != null && admitAddModel.getPermission() != "") {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> permissionMap = objectMapper.readValue(admitAddModel.getPermission(), Map.class);
            dataMap.put("permission", permissionMap);
        }


        ObjectMapper object = new ObjectMapper();
        String JsonData = object.writeValueAsString(dataMap);

        String url = "/v2/scene/admit/add";
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("场景编辑识别主体权限")
    @PostMapping(value = "/admitCookie")
    public R<String> admitCookie(AdmitAddModel admitAddModel) throws Exception {
        Map<String, Object> dataMap = new HashMap<>();
        if (admitAddModel.getSceneGuid() != null && admitAddModel.getSceneGuid() != "") {
            dataMap.put("sceneGuid", admitAddModel.getSceneGuid());
        }
        if (admitAddModel.getAdmitGuids() != null && admitAddModel.getAdmitGuids() != "") {
            dataMap.put("admitGuids", admitAddModel.getAdmitGuids());
        }
        if (admitAddModel.getType() != null && admitAddModel.getType() != "") {
            dataMap.put("type", admitAddModel.getType());
        }
        if (admitAddModel.getPassTime() != null && admitAddModel.getPassTime() != "") {
            dataMap.put("passTime", admitAddModel.getPassTime());
        }
        if (admitAddModel.getPermissionTime() != null && admitAddModel.getPermissionTime() != "") {
            dataMap.put("permissionTime", admitAddModel.getPermissionTime());
        }
        if (admitAddModel.getPermission() != null && admitAddModel.getPermission() != "") {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> permissionMap = objectMapper.readValue(admitAddModel.getPermission(), Map.class);
            dataMap.put("permission", permissionMap);
        }

        ObjectMapper object = new ObjectMapper();
        String JsonData = object.writeValueAsString(dataMap);

        String url = "/v2/scene/admit/cookie";
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("场景移除识别主体")
    @PostMapping(value = "/admitRemove")
    public R<String> admitRemove(AdmitRemoveOneModel admitRemoveOneModel) throws Exception {
        String JsonData = admitRemoveJson(admitRemoveOneModel.getSceneGuid(), admitRemoveOneModel.getAdmitArrays());
        String url = "/v2/scene/admit/remove";
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("查询场景中识别主体列表")
    @PostMapping(value = "/sceneAdmit")
    public R<String> sceneAdmit(@Validated SceneAdmit sceneAdmit) throws Exception {
        String url = "/v2/scene/admit";
        String JsonData = StringToJsonConverter.convertToJsonTow(sceneAdmit.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("清空场景中识别主体")
    @PostMapping(value = "/admitClear")
    public R<String> admitClear(@Validated AdmitClearModel admitClearModel) throws Exception {
        String url = "/v2/scene/admit/clear";
        String JsonData = StringToJsonConverter.convertToJsonTow(admitClearModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("场景绑定设备")
    @PostMapping(value = "/deviceAdd")
    public R<String> deviceAdd(@Validated DeviceAddModel deviceAddModel) throws Exception {
        String url = "/v2/scene/device/add";
        String JsonData = StringToJsonConverter.convertToJson(deviceAddModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("场景移除设备")
    @PostMapping(value = "/deviceRemove")
    public R<String> deviceRemove(@Validated DeviceAddModel deviceAddModel) throws Exception {
        String url = "/v2/scene/device/remove";
        String JsonData = StringToJsonConverter.convertToJsonTow(deviceAddModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    @ApiOperation("查询场景中设备列表")
    @PostMapping(value = "/sceneDevice")
    public R<String> sceneDevice(@Validated SceneDeviceModel sceneDeviceModel) throws Exception {
        String url = "/v2/scene/device";
        String JsonData = StringToJsonConverter.convertToJsonTow(sceneDeviceModel.toString());
        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, JsonData, token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }


    @ApiOperation("注册黑名单")
    @PostMapping(value = "/RegistrationBlacklist")
    public R<String> RegistrationBlacklist(String deviceNo, String url, String name) throws Exception {
//        创建场景
        SceneCreateModel sceneCreateModel = new SceneCreateModel();
        sceneCreateModel.setSceneName(deviceNo);
        sceneCreateModel.setSceneGuid("");
        sceneCreateModel.setAbility("");
        sceneCreateModel.setDuration("");
        R<String> sceneCreate = sceneCreate(sceneCreateModel);
        System.out.println("创建场景:" + sceneCreate);
        String onlinestate = JsonUtils.JsonData(String.valueOf(sceneCreate));
        JSONObject sceneCreateJsonObject = new JSONObject(onlinestate);
        JSONObject sceneCreateData = sceneCreateJsonObject.getJSONObject("data");
        String sceneGuid = sceneCreateData.getString("sceneGuid");
        JSONObject sceneCreateMo = new JSONObject(onlinestate);
        String sceneCreateMsg = sceneCreateMo.getString("msg");

        //场景绑定设备
        DeviceAddModel deviceAddModel = new DeviceAddModel();
        deviceAddModel.setSceneGuid(sceneGuid);
        deviceAddModel.setDeviceNos(deviceNo);
        R<String> deviceAdd = deviceAdd(deviceAddModel);
        System.out.println("场景绑定设备:" + deviceAdd);
        String onlinestateOne = JsonUtils.JsonData(String.valueOf(deviceAdd));
        JSONObject deviceAddMo = new JSONObject(onlinestateOne);
        String deviceAddMsg = deviceAddMo.getString("msg");

        //        识别主体创建
        name = UUID.randomUUID().toString();
        SubjectModel subjectModel = new SubjectModel();
        subjectModel.setName(name);
        subjectModel.setPhone("");
        subjectModel.setTag("");
        subjectModel.setCardNo("");
        subjectModel.setIdCardNo("");
        subjectModel.setPassword("");
        subjectModel.setAddition("");
        R<String> subject = admitCreate(subjectModel);
        String onlinestateTow = JsonUtils.JsonData(String.valueOf(subject));
        JSONObject jsonObject = new JSONObject(onlinestateTow);
        JSONObject data = jsonObject.getJSONObject("data");
        String admitGuid = data.getString("admitGuid");
        JSONObject subjectMo = new JSONObject(onlinestateTow);
        String subjectMsg = subjectMo.getString("msg");
        System.out.println("识别主体创建 subject: " + subject);
//        人像注册
        FaceRegisterModel faceRegisterModel = new FaceRegisterModel();
        faceRegisterModel.setAdmitGuid(admitGuid);
        faceRegisterModel.setUrl(url);
        faceRegisterModel.setBase64("");
        faceRegisterModel.setFaceTag("");
        faceRegisterModel.setFaceGuid("");
        R<String> faceRegister = faceRegister(faceRegisterModel);
        System.out.println("人像注册 faceRegister: " + faceRegister);
        String onlinestates = JsonUtils.JsonData(String.valueOf(faceRegister));

        JSONObject faceRegisterMo = new JSONObject(onlinestates);
        String faceRegisterMsg = faceRegisterMo.getString("msg");

//        设备授权识别主体
        AuthDevicemodel authDevicemodel = new AuthDevicemodel();
        authDevicemodel.setDeviceNo(deviceNo);
        authDevicemodel.setAdmitGuids(admitGuid);
        authDevicemodel.setType("");
        authDevicemodel.setPassTime("");
        authDevicemodel.setPermissionTime("");
        R<String> device = device(authDevicemodel);
        System.out.println("设备授权识别主体 device:" + device);
        String onlinestatef = JsonUtils.JsonData(String.valueOf(device));
        JSONObject deviceMo = new JSONObject(onlinestatef);
        String deviceMsg = deviceMo.getString("msg");

        if (subjectMsg.contains("success") && faceRegisterMsg.contains("success") && deviceMsg.contains("success") && sceneCreateMsg.contains("success") && deviceAddMsg.contains("success")) {
            return R.success(null, "拉黑成功");
        } else {
            return R.error("拉黑失败");
        }
    }

    @ApiOperation("拉出黑名单")
    @PostMapping(value = "/pullTheBlacklist")
    public R<String> pullTheBlacklist(String deviceNo, String admitGuid, String faceGuid, String sceneGuid) throws Exception {
//        设备销权识别主体
        AuthDevicemodel authDevicemodel = new AuthDevicemodel();
        authDevicemodel.setDeviceNo(deviceNo);
        authDevicemodel.setAdmitGuids(admitGuid);
        authDevicemodel.setType("");
        authDevicemodel.setPassTime("");
        authDevicemodel.setPermissionTime("");
        authDevicemodel.setPermission("");
        R<String> authDevice = deviceRevoke(authDevicemodel);
        String onlinestate = JsonUtils.JsonData(String.valueOf(authDevice));
        JSONObject authDeviceMo = new JSONObject(onlinestate);
        String authDeviceMsg = authDeviceMo.getString("msg");
        System.out.println("设备销权识别主体:" + authDevice);
//        人像删除
        FaceRegisterModel faceRegisterModel = new FaceRegisterModel();
        faceRegisterModel.setAdmitGuid(admitGuid);
        faceRegisterModel.setFaceGuid(faceGuid);
        faceRegisterModel.setFaceTag("");
        faceRegisterModel.setBase64("");
        faceRegisterModel.setUrl("");
        R<String> faceRegister = faceDelete(faceRegisterModel);
        String onlinestateOne = JsonUtils.JsonData(String.valueOf(faceRegister));
        JSONObject faceRegisterMo = new JSONObject(onlinestateOne);
        String faceRegisterMsg = faceRegisterMo.getString("msg");
        System.out.println("人像删除:" + faceRegister);
//        识别主体删除
        AdmitDelete admitDelete = new AdmitDelete();
        admitDelete.setAdmitGuids(admitGuid);
        R<String> admitDelete1 = admitDelete(admitDelete);
        String onlinestateTow = JsonUtils.JsonData(String.valueOf(admitDelete1));
        JSONObject admitDeleteMo = new JSONObject(onlinestateTow);
        String admitDeleteMsg = admitDeleteMo.getString("msg");
        System.out.println("识别主体删除" + admitDelete1);
//        场景移除设备
        DeviceAddModel deviceAddModel = new DeviceAddModel();
        deviceAddModel.setDeviceNos(deviceNo);
        deviceAddModel.setSceneGuid(sceneGuid);
        R<String> deviceAddMode = deviceRemove(deviceAddModel);
        String deviceAddModeOne = JsonUtils.JsonData(String.valueOf(deviceAddMode));
        JSONObject deviceAddModelMo = new JSONObject(deviceAddModeOne);
        String deviceAddModelMsg = deviceAddModelMo.getString("msg");
        System.out.println("场景移除设备" + deviceAddMode);
//        删除场景
        SceneCreateModel sceneCreateModel = new SceneCreateModel();
        sceneCreateModel.setSceneGuid(sceneGuid);
        sceneCreateModel.setSceneName("");
        sceneCreateModel.setAbility("");
        sceneCreateModel.setDuration("");
        R<String> sceneDelete = sceneDelete(sceneCreateModel);
        String sceneDeleteOne = JsonUtils.JsonData(String.valueOf(sceneDelete));
        JSONObject sceneDeleteMo = new JSONObject(sceneDeleteOne);
        String sceneDeleteMsg = sceneDeleteMo.getString("msg");
        System.out.println("删除场景" + sceneDelete);

        if (authDeviceMsg.contains("success") && admitDeleteMsg.contains("success") && deviceAddModelMsg.contains("success") && faceRegisterMsg.contains("success") && sceneDeleteMsg.contains("success")) {
            return R.success(null, "拉出成功");

        } else {
            return R.error("拉出失败");
        }
    }
}
